<template>
  <div class="table-container">
    <div style="display: flex; justify-content: center; align-items: center; width: 100%; height: 24px; font-weight: bold; font-size: 24px;">
      物料仓库
    </div>
    <div style="display: flex; justify-content: center; align-items: center; margin-top: 16px;">
      <el-input v-model="input" style="width: 80%;" placeholder="搜索材料" />
      <el-button type="primary" @click="searchMaterial">搜索</el-button>
    </div>
    <el-table :data="filteredTableData" style="width: 100%;">
      <el-table-column prop="materialId" label="材料编号" />
      <el-table-column prop="materialName" label="名称" />
      <el-table-column prop="quantity" label="数量" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="openTakeOutDialog(scope.row)">取出</el-button>
        </template>
      </el-table-column>
    </el-table>
    <p v-if="!filteredTableData.length && input">没有当前材料,可找管理员申请购买。</p>
  </div>
  <div class="bottom-fixed-button">
    <el-button type="primary" style="width: 90%;" @click="returnToTechnician">返回菜单</el-button>
  </div>

  <!-- 弹出框 -->
  <el-dialog v-model="dialogVisible" title="取出物料" width="80%">
    <div>材料编号: {{ selectedMaterial.materialId }}</div>
    <div>名称: {{ selectedMaterial.materialName }}</div>
    <div>当前数量: {{ selectedMaterial.quantity }}</div>
    <el-input v-model="takeOutQuantity" placeholder="输入要取出的数量" style="margin-top: 16px;" />
    <span slot="footer" class="dialog-footer">
      <div class="dialog-buttons">
        <el-button class="dialog-button" @click="dialogVisible = false">取消</el-button>
        <el-button class="dialog-button" type="primary" @click="confirmTakeOut">确认</el-button>
      </div>
    </span>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const input = ref('');
const tableData = ref([]);
const filteredTableData = ref([]);
const dialogVisible = ref(false);
const selectedMaterial = ref({
  materialId: null,
  materialName: '',
  quantity: 0
});
const takeOutQuantity = ref('');

const router = useRouter();
const returnToTechnician = () => {
  router.push('/technician/home');
};

// 获取数据
onMounted(async () => {
  try {
    const response = await axios.get('http://localhost:8005/mm/getData');
    tableData.value = response.data;
    filteredTableData.value = tableData.value;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
});

// 搜索功能
function searchMaterial() {
  if (!input.value) {
    filteredTableData.value = tableData.value;
  } else {
    filteredTableData.value = tableData.value.filter(item =>
        item.materialName.toLowerCase().includes(input.value.toLowerCase())
    );
  }
}

// 打开弹窗
function openTakeOutDialog(row) {
  selectedMaterial.value = { ...row };
  takeOutQuantity.value = ''; // 清空输入框
  dialogVisible.value = true;
}

// 确认取出物料
async function confirmTakeOut() {
  try {
    const materialId = selectedMaterial.value.materialId;
    const quantity = parseInt(takeOutQuantity.value, 10);

    // 确保 quantity 是整数并大于 0
    if (isNaN(quantity) || quantity <= 0) {
      throw new Error("请输入有效的数量");
    }

    const response = await axios.post(`http://localhost:8005/upMaterialsManage/${materialId}`, quantity, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    // 更新前端显示的库存数量
    selectedMaterial.value.quantity = response.data.quantity;

    // 更新表格中的数据
    const index = tableData.value.findIndex(item => item.materialId === materialId);
    if (index !== -1) {
      tableData.value[index].quantity = response.data.quantity;
    }

    // 关闭弹窗
    dialogVisible.value = false;

    // 清空输入框
    takeOutQuantity.value = '';

    // 显示成功消息
    ElMessage({
      message: '你已成功取出物料。',
      type: 'success',
    });
  } catch (error) {
    console.error('Error taking out material:', error);
  }
}
</script>

<style scoped>
.table-container {
  padding: 16px;
  max-height: calc(100vh - 96px);
  overflow-y: auto;
}
.bottom-fixed-button {
  height: 50px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  z-index: 1000;
  justify-content: center;
  align-items: center;
  padding-bottom: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 16px; /* 增加整体底部的间距 */
}
.dialog-buttons {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.dialog-button {
  width: 80px; /* 设置按钮宽度 */
  margin: 0 8px; /* 设置按钮与输入框之间的距离 */
}
</style>
